package com.qidian.buy.config.mqdemo;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 * @date 2023/9/15 11:12
 */
//@Configuration
public class RabbitTemplateConfig {
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        //这里传入的connectionFactory 是springboot注入的对象
        rabbitTemplate.setConnectionFactory(connectionFactory);
        // 开启Mandatory, 才能触发回调函数，无论消息推送结果如何都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        // 设置确认回调()  无论是否发送成功，这个回调都会执行
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("确认回调");
                System.out.println("ConfirmCallback: "+"相关数据：" + correlationData);
                System.out.println("ConfirmCallback: "+"确认情况：" + ack); // 成功是true，失败是false
                System.out.println("ConfirmCallback: "+"原因：" + cause);
            }
        });

        // 设置失败回调函数
        rabbitTemplate.setReturnsCallback((returned)->{
            System.out.println("失败回调:");
            System.out.println("message:" + returned.getMessage());
            System.out.println("replyCode:" + returned.getReplyCode());
            System.out.println("replyText:" + returned.getReplyText());
            System.out.println("exchange:" + returned.getExchange());
            System.out.println("routingKey:" + returned.getRoutingKey());
            System.out.println("returned:" + returned );
        });
        return rabbitTemplate;
    }
}
